package com.blvtphan.tipocketclubs.gui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.blvtphan.tipocketclubs.R;
import com.blvtphan.tipocketclubs.adapter.CacheImage;
import com.blvtphan.tipocketclubs.adapter.PreviewAdapter;
import com.blvtphan.tipocketclubs.api.ApiConstant;
import com.blvtphan.tipocketclubs.api.ApiHelper;
import com.blvtphan.tipocketclubs.custom.CustomButton;
import com.blvtphan.tipocketclubs.custom.CustomTextView;
import com.blvtphan.tipocketclubs.model.PlaceDetailModel;
import com.blvtphan.tipocketclubs.model.RewardsModel;
import com.blvtphan.tipocketclubs.system.UserSetting;
import com.blvtphan.tipocketclubs.util.ConnectionUtils;
import com.blvtphan.tipocketclubs.util.Constants;
import com.blvtphan.tipocketclubs.util.Constants.APIConstant;
import com.blvtphan.tipocketclubs.util.GeneralUtils;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingActivity;

public class MainActivity extends SlidingActivity implements OnClickListener {

	// private SideNavigationView sideMenu;
	private SlidingMenu mSlidingMenu;
	private Context mContext;
	private GridView mGridMerchants;
	private PreviewAdapter adapter;
	private Button mBtnPlaces, mBtnQrCodeScanner;
	private LinearLayout mLLNearby;
	private List<PlaceDetailModel> lstMerchantsModel;
	private LruCache<String, Bitmap> mMemoryCache;
	public static CacheImage mCache;
	private List<RewardsModel> lstRewardsModel;

	private CustomButton mBtnLogout;
	private CustomButton mBtnTracker;
	private CustomTextView mTxtUserFullname;
	
	private static final int DELAY_TIME = 7 * 1000;
	private static final int INTERVAL_TIME = 7 * 1000;
	private Timer timer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Activity
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_main);

		// Sliding Menu
		setBehindContentView(R.layout.sliding_menu_main);
		getSlidingMenu().setBehindOffset(100);
		mSlidingMenu = getSlidingMenu();
		mSlidingMenu.setMode(SlidingMenu.LEFT);
		mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		mSlidingMenu.setFadeDegree(0.35f);

		// Others
		mContext = this;
		// Get max available VM memory, exceeding this amount will throw an
		// OutOfMemory exception. Stored in kilobytes as LruCache takes an
		// int in its constructor.
		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

		// Use 1/8th of the available memory for this memory cache.
		final int cacheSize = maxMemory / 8;
		mCache = new CacheImage();
		mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
			@SuppressLint("NewApi")
			@Override
			protected int sizeOf(String key, Bitmap bitmap) {
				// The cache size will be measured in kilobytes rather than
				// number of items.
				return bitmap.getByteCount() / 1024;
			}
		};

		mCache.setmMemoryCache(mMemoryCache);

		initView();

		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.custom_title_bar);
		CustomTextView tvTitle = (CustomTextView) findViewById(R.id.txt_title_bar);
		tvTitle.setText(mContext.getString(R.string.title_home_screen));

		ImageView backIcon = (ImageView)findViewById(R.id.btn_back_activity);
		backIcon.setVisibility(View.GONE);
		
		ImageView menuIcon = (ImageView) findViewById(R.id.btn_side_menu);
		menuIcon.setVisibility(View.VISIBLE);
		menuIcon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// sideMenu.toggleMenu();
				mSlidingMenu.showMenu();
			}
		});

		// sideMenu = (SideNavigationView)
		// findViewById(R.id.side_navigation_view);
		// sideMenu.setMenuItems(R.menu.side_menu);
		// sideMenu.setMenuClickCallback(sideNavigationCallback);

		getDataFromServer();
	}

	/**
	 * 
	 */
	private void initView() {
		mGridMerchants = (GridView) findViewById(R.id.grid_list_merchants);
		mBtnPlaces = (CustomButton) findViewById(R.id.btn_places_cancham);
		mBtnQrCodeScanner = (CustomButton) findViewById(R.id.btn_qr_code);
		mLLNearby = (LinearLayout) findViewById(R.id.btn_search_nearby);
		mBtnPlaces.setOnClickListener(this);
		mBtnQrCodeScanner.setOnClickListener(this);
		mLLNearby.setOnClickListener(this);

		mBtnLogout = (CustomButton) findViewById(R.id.btn_side_logout);
		mBtnLogout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		mBtnTracker = (CustomButton) findViewById(R.id.btn_side_tracker);
		mBtnTracker.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext,
						TrackerSummaryActivity.class);
				startActivity(intent);
			}
		});

		mTxtUserFullname = (CustomTextView) findViewById(R.id.txt_user_fullname);
		mTxtUserFullname.setText(UserSetting.getInstance().getUserFullName());

		if (UserSetting.getInstance().getEmail().equals("guest@tipocket.com")) {
			mBtnQrCodeScanner.setVisibility(View.GONE);
			mBtnTracker.setVisibility(View.GONE);
		}
	}

	/**
	 * 
	 */
	private void getDataFromServer() {

		lstMerchantsModel = new ArrayList<PlaceDetailModel>();

		String url = ApiHelper.genAPI(ApiConstant.API.API_GET_MERCHANTS);
		// Fill PlanId and UserId on Url
		url = url.replace("{0}", UserSetting.getInstance().getToken());
		ConnectionUtils.ExcuteHttpGetThread excuteHttpGet = new ConnectionUtils.ExcuteHttpGetThread(
				mContext, mProcessGetMerchants, url, false);
		excuteHttpGet.execute();
	}

	/**
	 * Handler of get merchants
	 */
	private Handler mProcessGetMerchants = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case APIConstant.HANDLER_REQUEST_FAIL:
				break;
			case APIConstant.HANDLER_REQUEST_SUCCESS:
				String data = (String) msg.obj;

				lstMerchantsModel = ApiHelper.parseJSONGetAllMerchants(
						mContext, data);
				if (lstMerchantsModel != null) {
					initGridView();
				} else {

				}

				break;
			default:
				break;
			}
		}
	};

	/**
	 * 
	 */
	private void initGridView() {

		List<String> lstFirst9Logo = new ArrayList<String>();
		for(int i=0;i<9;i++) {
			lstFirst9Logo.add(lstMerchantsModel.get(i).getMarchantLogo());
		}
		adapter = new PreviewAdapter(mContext,
				lstFirst9Logo, mCache);
		mGridMerchants.setAdapter(adapter);
		
		mGridMerchants.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View v, int pos,
					long id) {
				Intent intent = new Intent(mContext, PlaceDetailsActivity.class);

				intent.putExtra(Constants.PlaceDetailExtras.ADDRESS,
						lstMerchantsModel.get(pos).getAddress());
				intent.putExtra(Constants.PlaceDetailExtras.LAT,
						lstMerchantsModel.get(pos).getLat());
				intent.putExtra(Constants.PlaceDetailExtras.LNG,
						lstMerchantsModel.get(pos).getLng());
				intent.putExtra(Constants.PlaceDetailExtras.NAME,
						lstMerchantsModel.get(pos).getName());
				intent.putExtra(Constants.PlaceDetailExtras.LOGO,
						lstMerchantsModel.get(pos).getMarchantLogo());

				lstRewardsModel = new ArrayList<RewardsModel>();
				lstRewardsModel = lstMerchantsModel.get(pos).getLstRewards();
				try {
					intent.putExtra(
							Constants.PlaceDetailExtras.LST_PLACE_REWARDS,
							GeneralUtils.object2Bytes(lstRewardsModel));
				} catch (IOException e) {
					e.printStackTrace();
				}

				startActivity(intent);
			}
		});
		if(lstMerchantsModel.size()>9) {
			RunMeTask task = new RunMeTask();
			timer = new Timer();
			timer.schedule(task, DELAY_TIME, INTERVAL_TIME);
		}

	}
	
	private List<Integer> getRandomIndex(int max, int range) {
		List<Integer> lstCardIndex = new ArrayList<Integer>();
		int j;
		Random r = new Random();
		for (int i = 0; i < range; i++) {
			do {
				j = r.nextInt(max);
			} while (isExisted(lstCardIndex, j));
			lstCardIndex.add(j);
		}
		return lstCardIndex;
	}
    
    /**
     * 
     * @param lst
     * @param i
     * @return
     */
    private boolean isExisted(List<Integer> lst, int i) {
		for (int item : lst) {
			if (i == item) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (MainActivity.mCache != null
				&& MainActivity.mCache.getmMemoryCache() != null) {
			Log.i("Before Eviction -- Cache's Size : ", MainActivity.mCache
					.getmMemoryCache().size() + "");
			MainActivity.mCache.getmMemoryCache().evictAll();
			Log.i("Cache's Size : ", MainActivity.mCache.getmMemoryCache()
					.size() + "");
		}
		if(timer!=null) 
			timer.cancel();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_places_cancham:
			startPlaceListActivity();
			break;
		case R.id.btn_search_nearby:
			startNearbySearchActivity();
			break;
		case R.id.btn_qr_code:
			Intent iQrCode = new Intent(mContext, QrCodeScannerActivity.class);
			startActivity(iQrCode);
			break;
		default:
			break;
		}
	}

	/**
	 * 
	 */
	private void startPlaceListActivity() {
		Intent intent = new Intent(mContext, PlacesListActivity.class);

		// Input data
//		try {
//			intent.putExtra(Constants.PlaceListExtras.LIST_PLACES,
//					GeneralUtils.object2Bytes(lstMerchantsModel));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}

		startActivity(intent);
	}

	/**
	 * 
	 */
	private void startNearbySearchActivity() {
		Intent intent = new Intent(mContext, NearbySearchActivity.class);

		// Input data
		try {
			intent.putExtra(Constants.NearbySearchExtras.LIST_PLACES,
					GeneralUtils.object2Bytes(lstMerchantsModel));
		} catch (IOException e) {
			e.printStackTrace();
		}

		startActivity(intent);
	}

	private class RunMeTask extends TimerTask {

		@Override
		public void run() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					final List<Integer> lstRandom = getRandomIndex(lstMerchantsModel.size(), 9);
					List<String> lstLogo = new ArrayList<String>();
					for (int item : lstRandom) {
						lstLogo.add(lstMerchantsModel.get(item).getMarchantLogo());
					}
					adapter = new PreviewAdapter(mContext, lstLogo, mCache);
					mGridMerchants.setAdapter(adapter);
					mGridMerchants.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {
							Intent intent = new Intent(mContext, PlaceDetailsActivity.class);

							intent.putExtra(Constants.PlaceDetailExtras.ADDRESS,
									lstMerchantsModel.get(lstRandom.get(pos)).getAddress());
							intent.putExtra(Constants.PlaceDetailExtras.LAT,
									lstMerchantsModel.get(lstRandom.get(pos)).getLat());
							intent.putExtra(Constants.PlaceDetailExtras.LNG,
									lstMerchantsModel.get(lstRandom.get(pos)).getLng());
							intent.putExtra(Constants.PlaceDetailExtras.NAME,
									lstMerchantsModel.get(lstRandom.get(pos)).getName());
							intent.putExtra(Constants.PlaceDetailExtras.LOGO,
									lstMerchantsModel.get(lstRandom.get(pos)).getMarchantLogo());

							lstRewardsModel = new ArrayList<RewardsModel>();
							lstRewardsModel = lstMerchantsModel.get(lstRandom.get(pos)).getLstRewards();
							try {
								intent.putExtra(
										Constants.PlaceDetailExtras.LST_PLACE_REWARDS,
										GeneralUtils.object2Bytes(lstRewardsModel));
							} catch (IOException e) {
								e.printStackTrace();
							}

							startActivity(intent);
						}
					});
				}
			});

		}
	}

}
